package Backend

import (
	"context"
	"crypto/md5"
	"fmt"
	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
	"hello/controllers/Base"
	"hello/wl"
	"math/rand"
	"os"
	"path"
	"time"
)

type UploadController struct {
	Base.BaseController
}

var key ="file"
//基本图片上传
func (this *UploadController) Index() {

	f, h, err1 := this.GetFile(key)//获取上传的文件

	if err1!=nil {
		panic(err1)
	}

	ext := path.Ext(h.Filename)
	//验证后缀名是否符合要求
	var AllowExtMap map[string]bool = map[string]bool{
		".jpg":true,
		".jpeg":true,
		".png":true,
	}
	if _,ok:=AllowExtMap[ext];!ok{
		this.Ctx.WriteString( "后缀名不符合上传要求" )
		return
	}
	//创建目录
	uploadDir := wl.UploadPath + time.Now().Format("2006/01/02/")
	err := os.MkdirAll( uploadDir , 777)
	if err != nil {
		this.Ctx.WriteString( fmt.Sprintf("%v",err) )
		return
	}
	//构造文件名称
	rand.Seed(time.Now().UnixNano())
	randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000 )
	hashName := md5.Sum( []byte( time.Now().Format("2006_01_02_15_04_05_") + randNum ) )

	fileName := fmt.Sprintf("%x",hashName) + ext
	//this.Ctx.WriteString(  fileName )

	fpath := uploadDir + fileName
	defer f.Close()//关闭上传的文件，不然的话会出现临时文件不能清除的情况
	err = this.SaveToFile("file", fpath)
	if err != nil {
		fmt.Println( fmt.Sprintf("%v",err) )
	}

	//this.AjaxSuccess(fpath)
	//将本地的文件上传到七牛云
	qiNiuName:=QiNiuUpload(fpath,fileName)

	this.AjaxSuccess(map[string]string{
						"host":wl.C("QiNiu::Host"),
						"fileName":qiNiuName,
						"url":wl.C("QiNiu::Host")+qiNiuName})

}



//ckedit 富文本上传 就是key 不一样
func (this *UploadController) CKIndex() {
	key="upload"
	this.Index()
}
//上传到七牛云
func  QiNiuUpload(path string,fileName string) string {

	accessKey := wl.C("QiNiu::accessKey")
	secretKey :=  wl.C("QiNiu::secretKey")
	localFile := path
	bucket := wl.C("QiNiu::bucket")
	key :=  wl.C("QiNiu::profix")+fileName
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac(accessKey, secretKey)
	upToken := putPolicy.UploadToken(mac)

	cfg := storage.Config{}
	cfg.Zone = &storage.ZoneHuadong
	cfg.UseHTTPS = false
	cfg.UseCdnDomains = false

	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}

	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": "github logo",
		},
	}
	err := formUploader.PutFile(context.Background(), &ret, upToken, key, localFile, &putExtra)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	fmt.Println(ret.Key, ret.Hash)

	return ret.Key

}
